package com.kr.weitao.util.redis;

import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Set;

/** Created by Abel on 2017/6/13. */
@Data
@Component
public class SetOps {

  @Autowired private RedisTemplate<Object, Object> redisTemplate;

  /**
   * 添加集合元素
   *
   * @param key
   * @param item
   * @return
   */
  public boolean addItem(String key, Object... item) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    setOperations.add(key, item);
    return true;
  }

  /**
   * 移除集合元素
   *
   * @param key
   * @param item
   * @return
   */
  public boolean removeItem(String key, Object... item) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    setOperations.remove(key, item);
    return true;
  }

  /**
   * 移除集合元素
   *
   * @param key
   * @param item
   * @return
   */
  public boolean getItem(String key, Object... item) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    setOperations.remove(key, item);
    return true;
  }
  /**
   * 获取集合长度
   *
   * @param key
   * @return
   */
  public Long getSize(String key) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    return setOperations.size(key);
  }

  /**
   * 获取两个key-value集合的合集
   *
   * @param key
   * @param otherKey
   * @return
   */
  public Set<Object> union(String key, String otherKey) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    return setOperations.union(key, otherKey);
  }

  /**
   * 获取一个key-value集合和传入集合的合集
   *
   * @param key
   * @param collection
   * @return
   */
  public Set<Object> union(String key, Collection<Object> collection) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    return setOperations.union(key, collection);
  }

  /**
   * 获取一个key-value集合和传入集合的合集
   *
   * @param key
   * @return
   */
  public Set<Object> getAll(String key) {
    SetOperations<Object, Object> setOperations = redisTemplate.opsForSet();
    return setOperations.members(key);
  }
}
